/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert.support;

import java.math.BigInteger;

import com.tengtong.duang.commons.base.AssertUtils;
import com.tengtong.duang.commons.convert.ConditionalConverter;
import com.tengtong.duang.commons.utils.ClassUtils;
import com.tengtong.duang.commons.utils.NumberUtils;

/**
 * 将 BigInteger 转换其他类型数字
 * 
 * @author jai
 *
 */
public class BigIntegerToNumberConverter implements ConditionalConverter {

	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#matches(java.lang.Class, java.lang.Class)
	 */
	@Override
	public boolean matches(Class<?> sourceType, Class<?> targetType) {
		AssertUtils.notNull(sourceType, "sourceType 不能为 null.");
		AssertUtils.notNull(targetType, "targetType 不能为 null.");
		
		return (BigInteger.class.equals(sourceType) && ClassUtils.isInheritance(targetType, Number.class));
	}

	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#convert(java.lang.Object, java.lang.Class)
	 */
	@Override
	public Object convert(Object source, Class<?> targetType) {
		if(source != null){
			Class<?> sourceType = source.getClass();
			BigInteger bi = (BigInteger)source;
			if(matches(sourceType, targetType)){
				if(Long.class.equals(targetType) || long.class.equals(targetType)){
					return bi.longValue();
				}
				
				if(Integer.class.equals(targetType) || int.class.equals(targetType)){
					return bi.intValue();
				}
				
				if(Double.class.equals(targetType) || double.class.equals(targetType)){
					return bi.doubleValue();
				}
				
				if(Float.class.equals(targetType) || float.class.equals(targetType)){
					return bi.floatValue();
				}
			}
		}
		return null;
	}

}
